import type { IUserLoginData } from "@/api/user";
import { login as loginApi } from "@/api/user";
import { removeToken, setToken } from "@/utils/auth";
import { useTagViews } from "./tagsView";

export const useUserStore = defineStore("user", () => {
  const state = reactive({
    token: ""
  });

  const login = async (userInfo: IUserLoginData) => {
    try {
      const { username, password } = userInfo;

      const response = await loginApi({
        username: username.trim(),
        password
      });

      const { data } = response;

      state.token = data.token;

      setToken(data.token);
    } catch (error) {
      return Promise.reject(error);
    }
  };

  const logout = () => {
    state.token = "";
    removeToken();
    // 清空所有可以清空的信息，比如保存的一些设置信息
    const tagsViewStore = useTagViews();
    tagsViewStore.delAllViews();
  };

  return {
    login,
    state,
    logout
  };
});
